//
//  BusinessTableViewController.m
//  EasyToTesco2.0
//
//  Created by 杨森 on 16/5/30.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "BusinessTableViewController.h"
#import "BusinessViewCell.h"
#import "BusinessDetailsController.h"

#import "BusinessModel.h"
#import "SelectCityView.h"

#import "BusinessSearchController.h"
#import "LogInViewController.h"

@interface BusinessTableViewController ()<UITableViewDelegate,UITableViewDataSource,SelectCityViewDelegate,UISearchBarDelegate>
{
    TopPullRefreshAnaimation *gifHeader;
    MBProgressHUD *progressHUD;
    NSUInteger refreshIndex;
    UIImageView *noDrawImage;
    //是否点击筛选
    BOOL _judgeSelect;
    //点击筛选上啦刷新
    BOOL _judgePost;
    NSString *_subCityStr;
    NSString *_townStr;
    
}

@property(nonatomic,strong)UITableView *businessView;

@property(nonatomic,strong)NSMutableArray *businessArray;

@property(nonatomic,strong)SelectCityView *selectCityView;

@property(nonatomic,strong)UISearchBar *searchBar;


@end

@implementation BusinessTableViewController

static NSString *const businessIdentifier = @"BusinessTableViewCell";

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear: animated];
    
    if ([ReadLoginData readLoginData].count) {
        [self.businessView reloadData];
    }
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [progressHUD hide:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addTableView];
    //上拉刷新
    [self addPullUpdateData];
    
    
    if (!_HOME_PUSH_Business) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"筛选" style:UIBarButtonItemStylePlain target:self action:@selector(selectCityButtonClick)];
        [self.navigationItem.leftBarButtonItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:15],NSFontAttributeName, nil] forState:UIControlStateNormal];
        [self.navigationItem.leftBarButtonItem setTintColor:[UIColor whiteColor]];
    }
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(businessSearch)];
    [self.navigationItem.rightBarButtonItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:15],NSFontAttributeName, nil] forState:UIControlStateNormal];
    [self.navigationItem.rightBarButtonItem setTintColor:[UIColor whiteColor]];
    
    //数据加载
    [self BusinessDetailsLoadDataCityStr:@"长沙" townStr:@""];
    //
    refreshIndex = 1;
    
}

#pragma mark 搜索
- (void)businessSearch
{
    BusinessSearchController *BusinessSearchVC = [[BusinessSearchController alloc] init];
    [self.navigationController pushForm:self.navigationController pushToAndHidden:BusinessSearchVC];
}


- (void)addTableView
{
    UITableView *businessView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStyleGrouped];
    self.businessView = businessView;
    [self.view addSubview:businessView];
    self.businessView.rowHeight = HEIGHT/5;
    businessView.backgroundColor = [UIColor whiteColor];
    businessView.delegate = self;
    businessView.dataSource = self;
    
    businessView.contentInset = UIEdgeInsetsMake(0,0,49,0);
}

- (void)selectCityButtonClick
{
    self.selectCityView = [[SelectCityView alloc] initWithFrame:CGRectMake(0,0, WIDTH, HEIGHT)];
    _selectCityView.delegate = self;
    [self.view addSubview:_selectCityView];
    [_selectCityView showPickerView];
}

#pragma mark 筛选城市
- (void)SelectCityViewCityStr:(NSString *)cityStr townStr:(NSString *)townStr
{
    _judgeSelect = YES;
    refreshIndex = 1;
    //截取字符  eg 丽水市 ->丽水
    NSString *subCityStr = [cityStr substringToIndex:[cityStr length] - 1];
    [self BusinessDetailsLoadDataCityStr:subCityStr townStr:townStr];
    
    _townStr = townStr;
    _subCityStr = subCityStr;
}

- (void)SelectCityViewCancle
{
    [_selectCityView dismissPickerView];
}

#pragma mark >>>>>>>>刷新
- (void)addPullUpdateData
{
    self.businessView.mj_footer = [TopPullRefreshAnaimation footerWithRefreshingTarget:self refreshingAction:@selector(BusinessDetailsLoadMoreData)];
    
    self.businessView.mj_header = [MJChiBaoZiHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];

}

- (void)BusinessDetailsLoadMoreData
{
    refreshIndex ++;
    
    if (_judgePost) {
        [self BusinessDetailsLoadDataCityStr:_subCityStr townStr:_townStr];
    }else{
        [self BusinessDetailsLoadDataCityStr:@"长沙" townStr:@""];
    }
    [self.businessView.mj_footer endRefreshing];
}

- (void)loadNewData
{
    refreshIndex = 1;
    [self.businessArray removeAllObjects];
    [self BusinessDetailsLoadDataCityStr:@"长沙" townStr:@""];
    [self.businessView.mj_header endRefreshing];
    [self.businessView.mj_footer resetNoMoreData];
}

- (void)BusinessDetailsLoadDataCityStr:(NSString *)cityStr townStr:(NSString *)townStr{
    
    //判断是否点击筛选
    if (_judgeSelect) {
        [self.businessArray removeAllObjects];
        refreshIndex = 1;
        _judgeSelect = false;
        _judgePost = YES;
    }
    
    //菊花加载
    progressHUD = [MBProgressHUD show:self.view andMessage:nil];
    [self.view addSubview:progressHUD];

    
    
    [noDrawImage removeFromSuperview];
    NSString *P = [NSString stringWithFormat:@"%ld",refreshIndex];
    
    NSDictionary *params = @{
                             @"city":cityStr,
                             @"county":townStr,
                             @"p":P
                             };
    NSLog(@"%@",params);
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/Business/lists" completeBlock:^(id object) {
        
        NSLog(@"%@",object);
        if (JudgeBackDataCode) {
            
            NSArray *arr = object[@"data"];
            for (NSDictionary *dict in arr) {
                BusinessModel *businessModel = [[BusinessModel alloc] initWithDictionary:dict error:nil];
                
                if (businessModel) {
                    [self.businessArray addObject:businessModel];
                } else{
                    //
                    [self.businessView.mj_footer endRefreshingWithNoMoreData];
                }
                
            }
            
        }else{
            
            //            if (!_judgeSelect) {
            //                //暂无地址(图)
            //                noDrawImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"noBussiness"]];
            //                [self.view addSubview:noDrawImage];
            //
            //                [noDrawImage mas_makeConstraints:^(MASConstraintMaker *make) {
            //                    make.centerX.equalTo(self.view.mas_centerX);
            //                    make.centerY.equalTo(self.view.mas_centerY).offset(-HEIGHT/10);
            //                    make.width.mas_equalTo(WIDTH/2);
            //                    make.height.mas_equalTo(HEIGHT/4);
            //                }];
            //            }
            
            [self.businessView.mj_footer endRefreshingWithNoMoreData];
        }
        [self.businessView reloadData];
        [progressHUD hide:YES];
        [progressHUD removeFromSuperViewOnHide];
    }];
    
    
}

- (void)touchUpInSideMessageButton:(UIButton *)button {
    
    NSLog(@"%@",self.businessArray[button.tag]);
    
    if ([JudgeUserLogInTool JudgeUserLonInStatus:self.view]) {
        BusinessModel *model = self.businessArray[button.tag];
        
        ChatViewController *chat = [[ChatViewController alloc] initWithConversationChatter:model.username conversationType:EMConversationTypeChat];
        chat.FromSellerNumber = model.username;
        chat.title = model.title;
        [self.navigationController pushForm:self.navigationController pushToAndHidden:chat];
    } else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"您尚未登录用户" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *SettingAction = [UIAlertAction actionWithTitle:@"去登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            LogInViewController *accountVC = [[LogInViewController alloc] init];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:accountVC];
            [self presentViewController:nav animated:YES completion:nil];
        }];
        [alert addAction:SettingAction];
        
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:cancelAction];
        
        [self presentViewController:alert animated:YES completion:nil];
    }
}



#pragma mark>>>>>>>>>>>数据源
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.businessArray.count >0 ? self.businessArray.count : 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    BusinessViewCell *cell = [tableView dequeueReusableCellWithIdentifier:businessIdentifier];
    
    if (cell==nil) {
        
        cell = [[BusinessViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:businessIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    BusinessModel *businessModel = self.businessArray[indexPath.row];
    
    if (businessModel.sdpic) {
        [cell.shopsImg sd_setImageWithURL:[NSURL URLWithString:businessModel.sdpic] placeholderImage:[UIImage imageNamed:@"placeholder"]];
    }else{
        cell.shopsImg.image = [UIImage imageNamed:@"placeholder"];
    }

    cell.shopsNameLabel.text = businessModel.title;
    cell.shopsDetailsLabel.text = businessModel.zycp;
    [cell.shopsAddress setTitle:businessModel.county forState:UIControlStateNormal];
    
    cell.messageButton.tag = indexPath.row;
    [cell.messageButton addTarget:self action:@selector(touchUpInSideMessageButton:) forControlEvents:UIControlEventTouchUpInside];
    
    if (JudgeInvididualOrSeller) {
        cell.messageButton.hidden = YES;
    } else {
        cell.messageButton.hidden = YES;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

#pragma mark>>>>>>>>>>>>代理
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BusinessDetailsController *detailVC = [[BusinessDetailsController alloc] init];
    BusinessModel *businessModel = self.businessArray[indexPath.row];
    detailVC.bussinessId = businessModel.replaceID;
    [self.navigationController pushForm:self.navigationController pushToAndHidden:detailVC];
}

- (NSMutableArray *)businessArray {
    if (!_businessArray) {
        _businessArray = [NSMutableArray array];
    }
    
    return _businessArray;
}

@end
